﻿package list;

import common.DoubleNode;

public class 删除双端链表的倒数第K个结点 {

	public static DoubleNode removeLastKthNode(DoubleNode head, int lastKth) {
		if (head == null || lastKth < 1) {
			return head;
		}
		DoubleNode cur = head;
		while (cur != null) {
			lastKth--;
			cur = cur.next;
		}
		if (lastKth == 0) {
			//如果last==0,说明要删除的节点是头节点
			head = head.next;
			head.last = null;
		}
		if(lastKth<0){
			//如果lastKth<0，说明要删除的节点存在，且在列表的中间
			cur =head;
			while(++lastKth!=0){
				cur =cur.next;
			}
			DoubleNode newNext = cur.next.next;
			cur.next = newNext;
			if(newNext!=null){
				newNext.last =cur;
			}
		}
		return head;
	}
}
